#!/bin/sh

die()
{
	echo "$*" >&2
	exit 1
}

info()
{
	echo "--- $*"
}

usage()
{
	echo "update [OPTIONS]"
	echo
	echo "Options:"
	echo " -f|--full              Full upgrade"
	echo " -d|--download-only     Download only"
}

full=0
download_only=0

while [ $# -ge 1 ]; do
	case "$1" in
	-f|--full)
		full=1
		;;
	-d|--download-only)
		download_only=1
		;;
	-h|--help)
		usage
		exit 0
		;;
	*)
		die "Unknown parameter: $1"
		;;
	esac
	shift
done

# Be nice
nice=19
renice $nice $$ >/dev/null || echo "Failed to renice to $nice" >&2

if [ $full -eq 0 ]; then
	upgrade_mode="upgrade"
else
	upgrade_mode="full-upgrade"
fi

info "Updating package list"
apt update || die "Update failed"

# Do the download and upgrade.
info "Performing '$upgrade_mode'"
dl_flags=
[ $download_only -ne 0 ] && dl_flags="--download-only"
apt $dl_flags --show-upgraded --verbose-versions "$upgrade_mode" ||\
	die "Upgrade failed"

# Exit here, if download only.
[ $download_only -ne 0 ] && exit 0

# Purge packages, if full upgrade.
if [ $full -ne 0 ]; then
	info "Purging old packages"
	apt-get autoremove --purge || die "Autoremove failed"
fi

info "Cleaning"
apt-get clean || die "Clean failed"

if command -v flatpak >/dev/null 2>&1; then
	info "Updating flatpaks"
	flatpak update || die "flatpak update failed"
	flatpak uninstall --unused || die "flatpak uninstall --unused failed"
fi

if command -v rpi-eeprom-update >/dev/null 2>&1; then
	info "Updating Raspberry Pi EEPROMs"
	rpi-eeprom-update -a || die "Raspberry Pi EEPROM update failed"
fi

if command -v podman >/dev/null 2>&1 && command -v systemctl >/dev/null 2>&1; then
	info "Updating podman containers"
	systemctl start podman-auto-update.service
fi

exit 0
